import pymysql
import config



print('lkjdsfljkdsfjklfdskjldasfjkldasfajlkfdas')
class DataBase:

    """ Этот класс представляет базу данных """

    def __init__(self, title, link, upvote, related_questions, answers):

        self.title = title
        self.link = link
        self.upvote = upvote
        self.related_questions = related_questions
        self.answers = answers

        self.connection = self.connect_to_database()
        self.start_process()
        self.close_connection()


    def connect_to_database(self):

        """ Подключиться к базе данных """

        try:

            connection = pymysql.connect(host='localhost',
                                        user=config.user,
                                        password=config.password,
                                        database='stackoverflow',
                                        cursorclass=pymysql.cursors.DictCursor)

            print('Successfully connected...')

            return connection

        except Exception as ex:

            print(ex)
            print('Connection refused...')


    def close_connection(self):

        """ Закрыть соединение """

        self.connection.close()
        print('Connection closed')


    def start_process(self):

        """ Процесс добавления данных в таблицу """

        #self.add_main_question()      # Добавляем главный вопрос в бд
        self.add_related_questions()  # Добавляем похожие вопросы в бд
        #self.add_answers()            # Добавляем ответы в бд


    def add_main_question(self):

        """ Добавить главный вопрос в бд """

        with self.connection.cursor() as cursor:

            sql_add_q = "INSERT INTO Questions (title, link, upvote) VALUES(%s, %s, %s);"
            cursor.execute(sql_add_q, (self.title, self.link, self.upvote))

            self.connection.commit()


    def add_related_questions(self):

        """ Добавляем похожие вопросы в бд """

        with self.connection.cursor() as cursor:

            for q in self.related_questions:

                sql_add_related_q = "INSERT INTO RelatedQuestions (vote, text, href) VALUES (%s, %s, %s);"
                cursor.execute(sql_add_related_q, (q[0], q[1], q[2]))

                self.connection.commit()


    def add_answers(self):

        """ Добавляем ответы к вопросу в бд """

        with self.connection.cursor() as cursor:

            for answer in self.answers:

                sql_add_answers = "INSERT INTO Answers(votes, content) VALUES (%s, %s);"
                cursor.execute(sql_add_answers, (answer[0], answer[1]))

                self.connection.commit()
